﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace CLEX.Server.Host.Helpers
{
    public sealed class PasswordHelper : IPasswordHelper
    {
        private static Random random = new Random();

        public string GenerateSalt(int length)
        {
            StringBuilder result = new StringBuilder(length);
            lock (random)
            {
                for (int i = 0; i < length; i++)
                {
                    result.Append((char)random.Next((int)'a', (int)'z' + 1));
                }
            }
            return result.ToString();
        }

        public string Hash(string password, string salt)
        {
            return Hash(password + salt);
        }

        private static string Hash(string value)
        {
            using (SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider())
            {
                byte[] hash = sha.ComputeHash(Encoding.ASCII.GetBytes(value));
                return BytesToHex(hash).ToLower();
            }
        }

        private static string BytesToHex(byte[] bytes)
        {
            return String.Concat(Array.ConvertAll(bytes, x => x.ToString("X2")));
        }

        public bool IsPassword(string hashedPassword, string salt, string password)
        {
            return hashedPassword == Hash(password, salt);
        }
    }
}